import { asyncRoutes, constantRoutes } from '@/router'
import { getMenu } from '@/api/user'

import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}

export function generaMenu(router, data, role) {
    data.forEach(item => {
        const menu = {
            path: item.path,
            component: item.openAddress === '' ? Layout : (resolve) => require([`@/views${item.openAddress}`], resolve),
            children: [],
            name: item.name,
            meta: { title: item.name, icon: item.icon, id: item.menuId, roles: [role] }
        }
        if (item.children) {
            generaMenu(menu.children, item.children)
        }
        router.unshift(menu)
    })
}

export function changeData(data) {
    data.forEach(item => {
        if (item.children.length === 0 && item.parentId === '1006') {
            item.children.push({ name: item.name, openAddress: item.openAddress, path: item.path.split('/')[2], icon: 'circle', children: [] })
            item.openAddress = '#'
            item.path = '/' + item.path.split('/')[1]
        }
    })
    return data
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */

export function filterAsyncRoutes(routes, roles) {
    const res = []
    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })
    // console.log(res)
    return res
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }

}

const actions = {
    generateRoutes({ commit, rootState }, roles) {
        return new Promise(resolve => {
            const loadMenuData = []
            /* rootState获取整个store模块里面的state*/
            getMenu(rootState.user.token).then((response) => {
                let data = response
                if (data.code === 0) {
                    console.log('未请求到数据...')
                } else {
                    const loginRole = data.data.role
                    data = data.data.menuList
                    changeData(data)
                    Object.assign(loadMenuData, data)
                    // generaMenu(asyncRoutes, loadMenuData, loginRole)
                    generaMenu(asyncRoutes, loadMenuData, loginRole)
                    console.log('routes is', asyncRoutes)
                    /* if (roles.includes('admin')) {
                       accessedRoutes = asyncRoutes || []
                    } else {
                       accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
                     }*/
                    const accessedRoutes = asyncRoutes || []
                    commit('SET_ROUTES', accessedRoutes)
                    resolve(accessedRoutes)
                }
            }).catch(error => {
                console.log(error)
            })
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
